<?php

namespace App\Http\Controllers;

use App\Http\Response\OKResponse;
use App\Models\PhonicsShare;
use App\Models\PhonicsStudent;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AdminPhonicsStudentController extends Controller
{

    public function manage(Request $request)
    {
        $this->validate(
            $request, [
                'pageSize' => 'integer|min:5|max:100',
                'page' => 'integer|min:1',
                'studentId' => 'integer',
            ]
        );

        $query = PhonicsStudent::query();
        if ($request->has('studentId')) {
            $query->where('student_id', intval($request->input('studentId')));
        }
        $total = $query->count();
        $pageSize = intval($request->input('pageSize', 10));
        $page = intval($request->input('page', 1));
        /**
         * @var $phonicsStudents PhonicsStudent[]
         */
        $phonicsStudents = $query->orderBy('created_at', 'desc')->skip($pageSize * ($page - 1))->take($pageSize)->get();
        $result = [];

        foreach ($phonicsStudents as $phonicsStudent) {
            $result[] = $phonicsStudent->toDisplay();
        }
        return new JsonResponse([
            'total' => $total,
            'page' => $page,
            'pageSize' => $pageSize,
            'result' => $result
        ]);
    }

    public function retrieveOne(Request $request, $id)
    {
        $request->merge(['id' => $id]);
        $this->validate($request, [
            'id' => 'required|integer|min:1'
        ]);
        $studentId = intval($id);

        $phonicsStudent = PhonicsStudent::createOrFetch($studentId);
        return new JsonResponse($phonicsStudent->toDisplay());
    }

    public function updatePrivilege(Request $request, $id)
    {
        $this->validate($request, [
            'sharePrivilege' => 'integer'
        ]);
        $sharePrivilege = intval($request->input('sharePrivilege', 1));
        $studentId = intval($id);
        $phonicsStudent = PhonicsStudent::createOrFetch($studentId);
        $phonicsStudent->setSharePrivilege($sharePrivilege);
        $phonicsStudent->save();
        return new OKResponse();
    }
}
